package com.fishingwithme.controllers;

import com.fishingwithme.domain.settings.SettingsService;
import cn.fishingwithme.infrastructure.dtos.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fishingwithme.infrastructure.dtos.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "/settings")
@PreAuthorize("hasRole('ROLE_ADMIN')")
@Tag(name = "Settings Management (Admin)", description = "Administrative APIs for system settings, rules, and agreements")
public class SettingsController {

    @Autowired
    private SettingsService settingsService;

    /**
     * 获取等级规则列表
     * GET /settings/levelRules
     */
    @GetMapping(path = "/levelRules")
    @Operation(
            summary = "Get level rules (Admin)",
            description = "Retrieve list of credit level rules - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Level rules retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<List<CreditLevelRuleDto>> getLevelRules() {
        List<CreditLevelRuleDto> rules = settingsService.getLevelRules();
        return DTO.success(rules);
    }

    /**
     * 获取积分规则列表
     * GET /settings/creditRules
     */
    @GetMapping(path = "/creditRules")
    @Operation(
            summary = "Get credit rules (Admin)",
            description = "Retrieve list of credit rules - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Credit rules retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<List<CreditRuleDto>> getCreditRules() {
        List<CreditRuleDto> rules = settingsService.getCreditRules();
        return DTO.success(rules);
    }

    /**
     * 分页获取反馈列表
     * GET /settings/feedback?pageNum=1&pageSize=10
     */
    @GetMapping(path = "/feedback")
    @Operation(
            summary = "Get feedback list (Admin)",
            description = "Retrieve paginated list of user feedback - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Feedback list retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<IPage<FeedbackListDto>> getFeedbackList(
            @Parameter(description = "Page number", example = "1")
            @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "Page size", example = "10")
            @RequestParam(defaultValue = "10") int pageSize) {
        IPage<FeedbackListDto> page = settingsService.getFeedbackList(pageNum, pageSize);
        return DTO.success(page);
    }

    /**
     * 获取协议列表
     * GET /settings/agr/all?pageNum=1&pageSize=10&type=1&enabled=true
     */
    @GetMapping(path = "/agr/all")
    @Operation(
            summary = "Get all agreements (Admin)",
            description = "Retrieve paginated list of agreements and privacy policies - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreements retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<IPage<AgrPpDto>> getAgr(
            @Parameter(description = "Page number", example = "1")
            @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "Page size", example = "10")
            @RequestParam(defaultValue = "10") int pageSize,
            @Parameter(description = "Agreement type filter")
            @RequestParam(required = false) String type,
            @Parameter(description = "Enabled status filter")
            @RequestParam(required = false) Boolean enabled) {
        IPage<AgrPpDto> agreements = settingsService.listAgrs(pageNum, pageSize, type, enabled);
        return DTO.success(agreements);
    }

    /**
     * 获取单个启用的协议
     * GET /settings/agr/single?type=T
     */
    @GetMapping(path = "/agr/single")
    @Operation(
            summary = "Get single agreement (Admin)",
            description = "Retrieve single enabled agreement by type - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "Agreement not found"
            )
    })
    public @ResponseBody DTO<AgrPpDto> getSingleAgr(
            @Parameter(description = "Agreement type", required = true, example = "T")
            @RequestParam(required = true) String type) {
        AgrPpDto agreement = settingsService.getAgrByType(type);
        return DTO.success(agreement);
    }

    /**
     * 根据类型查询所有版本号和启用状态的列表
     * GET /settings/agr/versions?type=T
     */
    @GetMapping(path = "/agr/versions")
    @Operation(
            summary = "Get agreement versions (Admin)",
            description = "Retrieve all versions and enabled status for agreement type - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement versions retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<List<AgrVersionDto>> getAgrVersions(
            @Parameter(description = "Agreement type", required = true, example = "T")
            @RequestParam(required = true) String type) {
        List<AgrVersionDto> versions = settingsService.getAgrVersionsByType(type);
        return DTO.success(versions);
    }

    /**
     * 保存隐私政策/用户协议
     * POST /settings/saveAgr
     */
    @PostMapping(path = "/agr/saveAgr")
    @Operation(
            summary = "Save agreement (Admin)",
            description = "Save new privacy policy or user agreement - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement saved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "400",
                    description = "Invalid agreement data"
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<Boolean> saveAgr(
            @Parameter(description = "Agreement save request", required = true)
            @RequestBody SaveAgrRequest request) {
        boolean result = settingsService.saveAgr(request);
        return DTO.success(result);
    }

    /**
     * 更新隐私政策/用户协议
     * POST /settings/updateAgr
     */
    @PostMapping(path = "/agr/updateAgr")
    @Operation(
            summary = "Update agreement (Admin)",
            description = "Update existing privacy policy or user agreement - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement updated successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "400",
                    description = "Invalid agreement data"
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            )
    })
    public @ResponseBody DTO<Boolean> updateAgr(
            @Parameter(description = "Agreement update request", required = true)
            @RequestBody UpdateAgrRequest request) {
        boolean result = settingsService.updateAgr(request);
        return DTO.success(result);
    }

    /**
     * 版本更新隐私政策/用户协议
     * POST /settings/newVersion
     */
    @GetMapping(path = "/agr/newVersion")
    @Operation(
            summary = "Create new agreement version (Admin)",
            description = "Create new version of privacy policy or user agreement - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "New agreement version created successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "Agreement not found"
            )
    })
    public @ResponseBody DTO<AgrPpDto> newVersion(
            @Parameter(description = "Agreement ID", required = true, example = "123")
            @RequestParam Long id) {
        AgrPpDto result = settingsService.newVersion(id);
        return DTO.success(result);
    }

    @GetMapping(path = "/agr/get")
    @Operation(
            summary = "Get agreement by ID (Admin)",
            description = "Retrieve agreement by ID - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement retrieved successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "Agreement not found"
            )
    })
    public @ResponseBody DTO<AgrPpDto> get(
            @Parameter(description = "Agreement ID", required = true, example = "123")
            @RequestParam Long id) {
        AgrPpDto result = settingsService.getAgrById(id);
        return DTO.success(result);
    }

    @GetMapping(path = "/agr/enable")
    @Operation(
            summary = "Enable/disable agreement (Admin)",
            description = "Enable or disable an agreement - requires admin role",
            security = @SecurityRequirement(name = "Bearer Authentication")
    )
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Agreement status updated successfully",
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = DTO.class)
                    )
            ),
            @ApiResponse(
                    responseCode = "401",
                    description = "Unauthorized - JWT token required"
            ),
            @ApiResponse(
                    responseCode = "403",
                    description = "Forbidden - Admin role required"
            ),
            @ApiResponse(
                    responseCode = "404",
                    description = "Agreement not found"
            )
    })
    public @ResponseBody DTO<Boolean> enable(
            @Parameter(description = "Agreement ID", required = true, example = "123")
            @RequestParam Long id, 
            @Parameter(description = "Enable status", required = true, example = "true")
            @RequestParam Boolean enabled) {
        return DTO.success(settingsService.enableAgr(id, enabled));
    }
}